import { PlusOutlined } from '@ant-design/icons';
import { Button, Form, Input, Upload, Image, Radio, Select, App } from 'antd'
import type { GetProp, RadioChangeEvent, UploadFile, UploadProps } from 'antd';
import React from 'react'
import API from '@/api'
import RichTextEditor from '@/components/RichTextEditor';
import { useAllChannelList } from '@/hooks/channel';
import { useNavigate } from 'react-router-dom';

const formRules = {
  title: [{ required: true, message: '请输入标题!' }],
  channel: [{ required: true, message: '请选择频道!' }],
  type: [{ required: true, message: '请选择图片数量!' }],
  content: [{ required: true, message: '请输入内容!' }]
}

const ArticlePublish = () => {
  const { message } = App.useApp();
  const navigate = useNavigate()
  const { allChannelList } = useAllChannelList()
  const richTextEditorRef = React.useRef<any>()
  const [limitImageNum, setLimitImageNum] = React.useState<number>(1)
  const [fileList, setFileList] = React.useState<UploadFile[]>([]);
  const [previewImage, setPreviewImage] = React.useState<string>('');
  
  const initialValues = {
    channel: allChannelList.length ? allChannelList[0].id : '',
    type: limitImageNum
  }

  const onBeforeUpload = (file: any) => {
    const isAllow = file.type === 'image/png' || file.type === 'image/jpeg';
    if (!isAllow) message.error(`${file.name}不属于jpg、png图片`);
    return isAllow;
  }

  const onChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {
    setFileList(newFileList)
  };

  const onPreview = async (file: UploadFile) => {
    setPreviewImage(file.thumbUrl || file.response.data.url);
  };

  const onRadioChange = (e: RadioChangeEvent) => {
    setLimitImageNum(e.target.value)
  }
  
  const onFinish = async (values: any) => {
    const submitData = {
      title: values.title,
      content: values.content,
      channel: values.channel,
      cover: {
        type: values.type,
        images: values.tempFile.fileList.map((item: any) => item.response ? item.response.data.url : item.thumbUrl)
      }
    }
    try {
    //   "data": {
    //     "id": "f1989a05-39b2-46a9-a726-6b8eeb7189d5"
    // },
    // "message": "OK"
      const res = await API.article.add(submitData)
      if (res.data) message.success('发布文章成功')
      else message.error('发布文章失败')
      setTimeout(() => {
        navigate('/')
      }, 2000)
    } catch(error) {
      console.error(error);
    }
  };
    
  return (
    <div>
      <Form name="normal_login" initialValues={ initialValues } onFinish={onFinish}>
        <Form.Item label="标题" name="title" hasFeedback rules={ formRules.title }>
          <Input placeholder="标题" />
        </Form.Item>
        <Form.Item label="频道" name="channel" hasFeedback rules={ formRules.channel }>
          <Select
            fieldNames={{ value: 'id', label: 'name' }}
            options={allChannelList}
          />
        </Form.Item>
        <Form.Item label="图片" name='type' hasFeedback rules={ formRules.type }>
          <Radio.Group value={ limitImageNum } buttonStyle="solid" onChange={ onRadioChange }>
            <Radio.Button value={1}>单图</Radio.Button>
            <Radio.Button value={3}>三图</Radio.Button>
            <Radio.Button value={0}>无图</Radio.Button>
          </Radio.Group>
        </Form.Item>
        {
          fileList.length <= limitImageNum &&
          <Form.Item name="tempFile" hasFeedback>
          <Upload
            action="http://geek.itheima.net/v1_0/upload"
            listType="picture-card"
            name='image'
            fileList={fileList}
            beforeUpload={onBeforeUpload}
            onPreview={onPreview}
            onChange={onChange}
          >
            {
              fileList.length < limitImageNum &&
              <button style={{ border: 0, background: 'none' }} type="button">
                <PlusOutlined />
              </button>
            }
          </Upload>
        </Form.Item>
        }
        <Form.Item label="内容" name='content' hasFeedback rules={ formRules.content }>
          <RichTextEditor ref={ richTextEditorRef } />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" className="login-form-button">提交</Button>
        </Form.Item>
      </Form>
      {
        previewImage &&
        <Image
          wrapperStyle={{ display: 'none' }} // 隐藏图片本体，只显示预览
          preview={{ visible: Boolean(previewImage), onVisibleChange: () => setPreviewImage('') }}
          src={previewImage}
        />
      }
    </div>
  )
}

export default ArticlePublish
